package com.me.study.javaCore.nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * SocketChannel：未完成
 */
public class SocketChannelTests {

    @Test
    public void test() throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress(9999));
        ByteBuffer buf = ByteBuffer.allocate(48);
        while(!socketChannel.finishConnect() ){
        }

        // int bytesRead = socketChannel.read(buf);
        // while (bytesRead != -1) {
        //     // 翻转 buffer，使其可读
        //     buf.flip();
        //     while(buf.hasRemaining()){
        //         System.out.print((char) buf.get());
        //     }
        //     // 翻转 buffer，使其可写
        //     buf.clear();
        //     bytesRead = socketChannel.read(buf);
        // }

        String newData = "New String to write to file..." + System.currentTimeMillis();
        buf.clear();
        buf.put(newData.getBytes());
        buf.flip();

        while(buf.hasRemaining()) {
            socketChannel.write(buf);
        }
    }

}
